package com.zc.controller;

import com.zc.entity.User;
import com.zc.mapper.UserMapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Date;
import java.util.List;

@Controller
public class UserContorller {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    UserMapper userMapper;
    @ResponseBody
    @DeleteMapping("/user/{id}")
    public  void userDelete(@PathVariable("id") Integer id)
    {

        userMapper.deleteByPrimaryKey(id);
        logger.info("删除了"+id+"号");
    }
    @GetMapping("/user")
    public String getUser(Model model){

        Collection<User> users = userMapper.selectAll();
        model.addAttribute("users",users);
        logger.info("USER get请求返回了");
        return "user/userlist01";
    }
    @PutMapping("/user")
    public String userUpdate(User user)
    {
        user.setCreatedate(new Date());
        userMapper.updateByPrimaryKey(user);
        logger.info("USER 修改请求返回了");
        logger.info(user.toString());
        return "user/userlist01";
    }
    @GetMapping("/userweihu")
    public String userWeihu(@Param("id")int id,
                            Model model){

        User user=userMapper.selectByPrimaryKey(id);
        model.addAttribute("user",user);
        logger.info("USER 维护请求返回了");
        return "user/userweihu";
    }
    @ResponseBody
    @PostMapping ("/user")
    public String addAllUser1(User user){

        user.setCreatedate(new Date());
        user.setId(userMapper.getMaxid()+1);
        userMapper.insert(user);
        logger.info(user.getRealname());
        logger.info("USER add请求返回了");
        return "success";
    }
    @ResponseBody
    @GetMapping("/user/{grade}")
    public List<User> getAllUser2(@PathVariable("grade") Integer grade){
        List<User> users=null;
        if(grade==0)
        {
            users=userMapper.selectAll();
        }else {
            users=userMapper.selectByGrade(grade);
        }
        logger.info("根据级别获取用户成功返回");
        return users;
    }

}
